package com.purang.web.filter;

import com.purang.web.bean.SecurityPermission;
import com.purang.web.bean.SecurityPermissionFactory;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PermissionFilter extends GenericFilter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletContext servletContext = getServletContext();
        Map<String, List<SecurityPermission>> permissionMap =
                (Map<String, List<SecurityPermission>>) servletContext.getAttribute("permissionMap");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String servletPath = request.getServletPath();
        List<SecurityPermission> needPermissions = permissionMap.get(servletPath);
        if(needPermissions == null || needPermissions.size() == 0) {
            filterChain.doFilter(request, response);
        }
        String authorization = request.getParameter("Authorization");
        List<SecurityPermission> havePermissions = new ArrayList<>();
        if (!"".equals(authorization) && authorization != null) {
            havePermissions = Arrays.asList(authorization.split(";")).stream().
                    map(a -> SecurityPermissionFactory.getSecurityPermission(a)).collect(Collectors.toList());
        }
        List<SecurityPermission> finalHavePermissions = havePermissions;
        if (needPermissions.stream().allMatch(a -> finalHavePermissions.contains(a)) || havePermissions.contains(SecurityPermissionFactory.getSecurityPermission("admin"))) {
            filterChain.doFilter(request, response);
        } else {
            response.setContentType("text/html");
            response.getWriter().println("<h1>" + "sorry,you don have the permission" + "</h1>");
        }
    }
}
